package com.ll.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ll.blog.common.*;
import com.ll.blog.contant.ExceptionEnum;
import com.ll.blog.entity.User;
import com.ll.blog.filter.UserFilter;
import com.ll.blog.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Null;
import javax.validation.constraints.Pattern;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 *用户模块
 * @author 
 * @since 2023-10-25
 */
@RestController
@Validated
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    Sms sms;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 登录接口
     * @param username 用户名或邮箱
     * @param password 密码
     */
    @PostMapping("login")
    @Cacheable("login")
    public ApiResponse login(@NotEmpty(message = "用户名不能为空") String username,@NotEmpty(message = "密码不能为空") String password) throws NoSuchAlgorithmException {
        LambdaQueryWrapper<User> wrapper = new QueryWrapper<User>().lambda();
        wrapper.eq(User::getEmail,username).or().eq(User::getUsername,username);
        User user = userService.getOne(wrapper);
        if(user == null){
            return ApiResponse.error(ExceptionEnum.USER_NO_EXIST);
        }
        String str = MD5Utils.getMD5Str(password);
        if (!Objects.equals(str, user.getPassword())) {
            return ApiResponse.error(ExceptionEnum.PASSWORD_ERROR);
        }
        String token = Token.createJWT(user);
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token,token,6,TimeUnit.HOURS);
        return ApiResponse.success("登录成功",token);
    }

    /**
     * 注册模块
     * @param username 用户名
     * @param password 密码
     * @return
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("register")
    public  ApiResponse register(@NotEmpty(message = "用户名不能为空") String username,
                                 @NotEmpty(message = "密码不能为空") String password,
                                 @NotEmpty(message = "邮箱不能为空")
                                     @Pattern(regexp = "[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$",message = "请输入正确的邮箱") String email,
                                 @NotEmpty(message = "邮箱验证码不能为空") String code

    ) throws NoSuchAlgorithmException {
        LambdaQueryWrapper<User> wrapper = new QueryWrapper<User>().lambda();
         wrapper.eq(User::getEmail, email);
        User user1 = userService.getOne(wrapper);
        if(user1 != null){
            return ApiResponse.error(ExceptionEnum.EMAIL_EXIST);
        }
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String s = operations.get(email);
        if (s == null || !Objects.equals(s, code)){
            return ApiResponse.error(ExceptionEnum.CODE_ERROR);
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(MD5Utils.getMD5Str(password));
        user.setRole(0);
        user.setEmail(email);
        boolean save = userService.save(user);
        if (save){
            return ApiResponse.success("注册成功");
        }
        return ApiResponse.error(ExceptionEnum.SAVE_ERROR);
    }

    /**
     * 获取邮箱验证码
     * @param email 要发送验证码的邮箱
     */
    @PostMapping("/getSmsCode")
    public ApiResponse getSmsCode(@NotEmpty(message = "邮箱不能为空")
                                  @Pattern(regexp = "[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$",message = "请输入正确的邮箱") String email) throws MessagingException {
        String code = sms.getSmsCode();
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(email,code,1, TimeUnit.MINUTES);
        sms.send(code,email);
        return ApiResponse.success("发送成功");
    }

    /**
     * 退出登录
     * @param token
     * @return
     */
    @PostMapping("/logout")

    public ApiResponse Logout(@RequestHeader("Authorization") String token){
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return ApiResponse.success();
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public ApiResponse getUserInfo(@RequestHeader("Authorization") String token){
        Integer userId = UserFilter.getUser();
        User user = userService.getById(userId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",user.getId());
        map.put("Username",user.getUsername());
        map.put("avatar",user.getAvatar());
        return ApiResponse.success(map);
    }

}
